package com.example.gyj.controller;

import com.example.gyj.entity.User;
import com.example.gyj.redis.GoodsKey;
import com.example.gyj.result.Result;
import com.example.gyj.service.GoodsService;
import com.example.gyj.service.RedisService;
import com.example.gyj.vo.GoodsDetailVo;
import com.example.gyj.vo.GoodsVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.spring4.context.SpringWebContext;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 商品controller
 * @author Gao
 * @date 2018/10/21
 */
@Controller
@RequestMapping("/goods")
public class GoodsController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RedisService redisService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * 商品列表页
     * QPS:1267 load:15 mysql
     * 5000 * 10
     * QPS:2884, load:5 新的加入了redis后的结果
     * @param model
     * @param user
     */
    @GetMapping(value = "/toList")
    public String list(Model model, User user) {
        model.addAttribute("user", user);
        List<GoodsVo> goodsList = goodsService.listGoodsVo();
        model.addAttribute("goodsList", goodsList);
        return "goods_list";
    }

    /**
     * 商品列表页面缓存
     * @param request
     * @param response
     * @param model
     * @param user
     */
    @GetMapping(value = "/toList1", produces = "text/html")
    @ResponseBody
    public String list(HttpServletRequest request, HttpServletResponse response, Model model, User user) {
        model.addAttribute("user", user);
        //取缓存
        String html = redisService.get(GoodsKey.getGoodsList, "", String.class);
        if (StringUtils.isNotEmpty(html)) {
            return html;
        }
        List<GoodsVo> goodsVoList = goodsService.listGoodsVo();
        model.addAttribute("goodsVoList", goodsVoList);
        SpringWebContext ctx = new SpringWebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap(), applicationContext);
        //手动渲染
        html = thymeleafViewResolver.getTemplateEngine().process("goods_list", ctx);
        if (StringUtils.isNotEmpty(html)) {
            redisService.set(GoodsKey.getGoodsList, "", html);
        }
        return html;
    }


    /**
     * 根据商品Id获取商品详情页
     * @param request
     * @param response
     * @param model
     * @param user
     * @param goodsId
     */
    @GetMapping(value = "/detail/{goodsId}")
    @ResponseBody
    public Result<GoodsDetailVo> detail(HttpServletRequest request, HttpServletResponse response,
                                        Model model, User user, @PathVariable("goodsId") long goodsId) {
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);

        // 开始时间
        long startAt = goods.getStartDate().getTime();
        // 结束时间
        long endAt = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();
        // 秒杀状态,剩余秒数
        int seckillStatus = 0, remainSeconds = 0;
        // 秒杀还没有开始
        if (now < startAt) {
            seckillStatus = 0;
            remainSeconds = (int) ((startAt - now) / 1000);
            // 秒杀已经结束
        } else if (now > endAt) {
            seckillStatus = 2;
            remainSeconds = -1;
            // 秒杀进行中
        } else {
            seckillStatus = 1;
            remainSeconds = 0;
        }

        GoodsDetailVo vo = new GoodsDetailVo();
        vo.setGoods(goods);
        vo.setUser(user);
        vo.setSeckillStatus(seckillStatus);
        vo.setRemainSeconds(remainSeconds);

        return Result.success(vo);
    }

    @GetMapping(value = "/detail1/{goodsId}", produces = "text/html")
    @ResponseBody
    public String detail(@PathVariable("goodsId") long goodsId, HttpServletRequest request, HttpServletResponse response,
                         Model model, User user) {
        model.addAttribute("user", user);

        //取缓存
        String html = redisService.get(GoodsKey.getGetGoodsDetail, "" + goodsId, String.class);
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        //手动渲染
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        model.addAttribute("goods", goods);

        long startAt = goods.getStartDate().getTime();
        long endAt = goods.getEndDate().getTime();
        long now = System.currentTimeMillis();

        int miaoshaStatus = 0;
        int remainSeconds = 0;
        if (now < startAt) {//秒杀还没开始，倒计时
            miaoshaStatus = 0;
            remainSeconds = (int) ((startAt - now) / 1000);
        } else if (now > endAt) {//秒杀已经结束
            miaoshaStatus = 2;
            remainSeconds = -1;
        } else {//秒杀进行中
            miaoshaStatus = 1;
            remainSeconds = 0;
        }
        model.addAttribute("miaoshaStatus", miaoshaStatus);
        model.addAttribute("remainSeconds", remainSeconds);

        SpringWebContext ctx = new SpringWebContext(request, response,
                request.getServletContext(), request.getLocale(), model.asMap(), applicationContext);
        html = thymeleafViewResolver.getTemplateEngine().process("goods_detail", ctx);
        if (!StringUtils.isEmpty(html)) {
            redisService.set(GoodsKey.getGetGoodsDetail, "" + goodsId, html);
        }

        return html;
    }
}
